<?php

namespace app\admin\controller\factory;

use app\common\model\goods\Goods;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\factory\Goods as fGoods;
use app\common\model\sales\CheckoutGoods;
use app\common\controller\Backend;
use app\common\model\customer\Customer;
use app\common\model\Storehouse;
use app\common\model\data\Voucher;
use app\common\model\supplier\Supplier;
use app\web\controller\Wweixin;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Sales extends Backend
{
    
    /**
     * Slip模型对象
     * @var
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\factory\Sales;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = $this->request->get("filter");
            $filter = (array)json_decode($filter, true);
            $where=[];


            if(!empty($filter)){
                foreach ($filter as $key =>$value){
                    if($key == 'goods_name'){
                        $gids = Db::name('goods')->where(array('title'=>array('like','%'.trim($value).'%')))->field('id')->select();
                        $ids = [];
                        foreach ($gids as $v){
                            $ids[]= $v['id'];
                        }
                        $fids = Db::name('factory_sales_goods')->where(array('goods_id'=>array('in',$ids)))->column('factory_sales_id');
                        $where['ss.id'] = array('in',$fids);
                    }
                    if($key == 'number'){
                        $where['ss.number'] = array('like','%'.$value.'%');
                    }
                    if($key == 'operator'){
                        $where['ss.operator'] = array('like','%'.$value.'%');
                    }
                    if($key == 'company'){
                        $where['ss.company'] = array('like','%'.$value.'%');
                    }
                    if($key == 'id'){
                        $where['ss.id'] = $value;
                    }
                    if($key == 'status'){
                        $where['ss.status'] = $value;
                    }
                    if($key == 'sl_number'){
                        $slrows = Db::name('sales_slip')->where(array('number'=>array('like','%'.$value.'%')))->select();
                        if(!empty($slrows)){
                            foreach ($slrows as $v){
                                $slids[] = $v['id'];
                            }
                            $where['ss.sales_slip_id'] = array('in',$slids);
                        }
                    }

                    if($key == 'ccompany'){
                        $where1['nickname'] = array('like','%'.$value.'%');
//                        exit;
                        $list =  Customer::where($where1)->field('id')->select();

                        if(!empty($list)){
                            foreach ($list as $v){
                                $ids[] = $v['id'];
                            }
                            $where['ss.customer_id'] = array('in',$ids);
                        }
                    }
                    if($key == 'snickname'){
                        $where1['nickname'] = array('like','%'.$value.'%');
//                        exit;
                        $list =  Supplier::where($where1)->field('id')->select();

                        if(!empty($list)){
                            foreach ($list as $v){
                                $ids[] = $v['id'];
                            }
                            $where['ss.supplier_id'] = array('in',$ids);
                        }
                    }
                    if($key == 'createtime'){
                        $arr = explode(' - ', $value);
                        $where['ss.createtime'] = array('between time',$arr);
                    }
                    if($key == 'deliverytime'){
                        $arr = explode(' - ', $value);
                        $where['ss.deliverytime'] = array('between time',$arr);
                    }
                }
            }

            if(isset(session('admin')['storehouse_id']) && session('admin')['storehouse_id'] >0){
                $storehouse_id = session('admin')['storehouse_id'];
                $where['ss.storehouse_id'] = $storehouse_id;
            }else{
//                $row = Db::name('storehouse')->where(array('is_default'=>1))->find();
//                if(!empty($row)){
//                    $storehouse_id = $row['id'];
//                    $where['ss.storehouse_id'] = $storehouse_id;
//                }
            }

            $offset = input('offset');
            $limit = input('limit');
            $list = Db::name('factory_sales')
                ->field('ss.*,c.company as ccompany,s.nickname  as snickname,sl.number as sl_number')
                ->alias('ss')
                ->where($where)
                ->join('zax_customer c','ss.customer_id = c.id')
                ->join('zax_supplier s','ss.supplier_id = s.id','LEFT')
                ->join('zax_sales_slip sl','ss.sales_slip_id = sl.id','LEFT')
                ->limit($offset,$limit)
                ->order('ss.id','DESC')
                ->select();
            $total= Db::name('factory_sales')
                ->alias('ss')
                ->where($where)
                ->join('customer c','ss.customer_id = c.id')
                ->join('zax_supplier s','ss.supplier_id = s.id','LEFT')
                ->join('zax_sales_slip sl','ss.sales_slip_id = sl.id','LEFT')
                ->count();



            $house = new Storehouse();
            $houses = $house->select();

            $status = $this->model->slip_status();
            foreach ($list as $k => $v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $status[$v['status']];
                foreach ($houses as $val){
                    if($v['storehouse_id'] == $val['id']){
                        $list[$k]['house_name'] = $val['name'];
                    }
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function getcount(){
       $filter = input();
        $where=[];
        $where['ss.status'] = array('<',6);
        foreach ($filter as $key =>$value){
            if($key == 'number' && !empty($value)){
                $where['ss.number'] = array('like','%'.$value.'%');
            }
            if($key == 'operator' && !empty($value)){
                $where['ss.operator'] = array('like','%'.$value.'%');
            }
            if($key == 'company' && !empty($value)){
                $where['ss.company'] = array('like','%'.$value.'%');
            }
            if($key == 'id' && !empty($value)){
                $where['ss.id'] = $value;
            }
            if($key == 'status' && !empty($value)){
                $where['ss.status'] = $value;
            }

            if($key == 'nickname' && !empty($value)){
                $where1['nickname'] = array('like','%'.$value.'%');
//                        exit;
                $list =  Customer::where($where1)->field('id')->select();

                if(!empty($list)){
                    foreach ($list as $v){
                        $ids[] = $v['id'];
                    }
                    $where['ss.customer_id'] = array('in',$ids);
                }
            }
            if($key == 'createtime' && !empty($value)){
                $arr = explode(' - ', $value);
                $where['ss.createtime'] = array('between time',$arr);
            }
            if($key == 'deliverytime' && !empty($value)){
                $arr = explode(' - ', $value);
                $where['ss.deliverytime'] = array('between time',$arr);
            }
        }
        $num = Db::name('factory_sales')
            ->alias('ss')
            ->where($where)
            ->join('customer c','ss.customer_id = c.id')
            ->sum('sales_num');
        $price = Db::name('factory_sales')
            ->alias('ss')
            ->where($where)
            ->join('customer c','ss.customer_id = c.id')
            ->sum('actual_cost');
        $result = array('num'=>$num,'price'=>$price);

        return json($result);
    }

    public function add()
    {
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
        if ($this->request->isAjax()) {
            $customer_id = input('customer_id/d',0);
            if(empty($customer_id)){
                $this->error('客户不能为空');
            }

            $supplier_id = input('supplier_id/d',0);
//            if(empty($supplier_id)){
//                $this->error('供应商不能为空');
//            }
            $tax = floatval(input('tax'));
            if(!is_float($tax) || $tax >13){
                $this->error('请检查税费');
            }
            $explain = input('explain');
            $mobile = input('mobile');
            $address = input('address');
            $contacts = input('contacts');
            $allfare = input('allfare/d');
            $actual_cost = input('actual_cost');
            if(empty($actual_cost)){
                $this->error('费用计算错误');
            }
            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            $sale_num = 0;

            $sdata = $params['row'];
            $allprice = 0;
            foreach ($sdata as $k=> $v){
//                if(!empty($v['tax'])){
//                    if(!is_float($v['tax'])){
//                        $this->error('商品'.$v['goods_id'].'税费设置有误');
//                    }
//                }
//                $sdata[$k]['tax'] = floatval(input('tax'));
                $allprice+=$v['sfhj'];
                $sale_num +=$v['goods_num'];
            }
//            if($allprice+$allfare != $actual_cost){
            if(!compare($allprice+$allfare,$actual_cost)){
                $this->error('计算费用错误');
            }
            $num = Db::name('factory_sales')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            if(isset(session('admin')['storehouse_id']) && session('admin')['storehouse_id'] >0){
                $storehouse_id = session('admin')['storehouse_id'];
            }else{
                $row = Db::name('storehouse')->where(array('is_default'=>1))->find();
                if(empty($row)){
                    $this->error('请设置默认仓库');
                }
                $storehouse_id = $row['id'];
            }

            $saledata = array(
                'number'=>'ZF-T-'.date('Y-m-d').'-'.getnumber($num),
                'actual_cost'=>$actual_cost,
                'customer_id'=>$customer_id,
                'supplier_id'=>$supplier_id,
                'explain'=>$explain,
                'address'=>$address,
                'mobile'=>$mobile,
                'allfare'=>$allfare,
                'contacts'=>$contacts,
                'tax'=>$tax,
                'sales_num'=>$sale_num,
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'storehouse_id'=>$storehouse_id,
            );

            Db::startTrans();
            try {
                $this->model->save($saledata);

                if(!$this->model->id){
                    throw new Exception('添加失败');
                }
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$storehouse_id,
                    'bill_id'=>$this->model->id,
                    'type'=>12,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));


                $gdata = [];
                foreach ($sdata as $k => $v) {
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'ht_price' => $v['ht_price'],
                        'tax' => $v['tax'],
                        'sfhj' => $v['sfhj'],
                        'remark' => $v['remark'],
                        'customer_id' => $customer_id,
                        'supplier_id'=>$supplier_id,
                        'factory_sales_id' => $this->model->id,
                        'createtime'=>time(),
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'storehouse_id'=>$storehouse_id,
                    );
                    Db::name('goods')->where(array('id'=>$v['goods_id']))->setInc('weigh');

                }

                $sGoods = new fGoods;
                $sGoods->saveAll($gdata);

                $wx = new Wweixin;
                $wx->senmsg(12);

                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'入库成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('storehouse_id',empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id']);

        return $this->view->fetch();
    }
    public function seach(){
        $house_id = input('house_id/d',0);

        $this->assign('house_id',$house_id);
        return $this->view->fetch();
    }
    public function getgood($ids){
        $good = new Goods();
        $ginfo = $good->where(array('id'=>$ids))->find();
        return $ginfo;
    }
    public function detail($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }

        if ($this->request->isAjax()) {
            $status = input('status/d',0);
            if(!$status){
                $this->error('非法操作');
            }

            Db::startTrans();
            try {
                $res = $this->model->save(array('status' => $status), array('id' => $ids));
                if ($res) {
                    $type = 1;
                    if($status == 6){ //审核拒绝 退回销售单
                        $type = 2;
                        $fGoods = new fGoods();
                        $ress = $fGoods->save(array('status'=>0),array('factory_sales_id'=>$ids));
                        if (!$ress) {
                            throw new Exception('数据异常');
                        }
                        if(!empty($row['sales_slip_id'])){
                            $this->returnslip($row);
                        }
                    }
                    //审核通过 生成订单明细
                    if($status == 3){
                        $this->addlog($ids);
                        $sales_log_id = Db::name('customer_sales_log')->insertGetId(array(
                                'customer_id'=>$row['customer_id'],
                                'type'=>'厂家直发单',
                                'type_id'=>2,
                                'number'=>$row['number'],
                                'source_id'=>$row['id'],
                                'createtime'=>time(),
                                'admin_id'=>$row['admin_id'],
                                'group_id'=>$row['group_id'],
                                'company'=>$row['company'],
                                'operator'=>$row['operator'],
                                'sales_num'=>$row['sales_num'],
                                'actual_cost'=>$row['actual_cost'],
                                'storehouse_id'=>$row['storehouse_id'],
                            ));
                        $glists = Db::name('factory_sales_goods')->where(array('factory_sales_id'=>$ids))->select();
                        foreach ($glists as $v) {
                            Db::name('goods_sales_log')->insert(array(
                                'goods_id' => $v['goods_id'],
                                'type' => '厂家直发',
                                'type_id' => 2,
                                'number' => $row['number'],
                                'source_id' => $row['id'],
                                'createtime' => time(),
                                'sales_log_id'=>$sales_log_id,
                                'admin_id'=>$row['admin_id'],
                                'group_id'=>$row['group_id'],
                                'company'=>$row['company'],
                                'operator'=>$row['operator'],
                                'storehouse_id'=>$row['storehouse_id'],
                            ));
                        }
                    }


                    Db::name('examine_log')->insert(array(
                        'admin_id'=>session('admin')['id'],
                        'type'=>$type,
                        'createtime'=>time(),
                        'controller'=>'factory/sales',
                        'source_id'=>$ids,
                        'source'=>12,
                        'remark'=>'厂家直发',
                        'number'=>isset($row['number'])?$row['number']:'',
                    ));
                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '成功'
                    );
                }
                throw new Exception('错误异常');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }



        $rows = Db::name('factory_sales_goods')
            ->field(' goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,sg.status,factory_sales_id,unit_price,unit_tax,unit_ht_price,sfhj')
            ->alias('sg')
            ->where(array('factory_sales_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
//        $sale_money = 0;
        $supplier_cost = 0;
        $money = array(
            'sale'=>0,
            'purche'=>0,
        );
        $taxmoney = array(
            'sale'=>0,
            'purche'=>0,
        );
        $allmoney = array(
            'sale'=>0,
            'purche'=>0,
        );




        $allnum = 0;
        foreach ($rows as &$v){
            $v['tax_all'] = round(($v['unit_ht_price']/($v['unit_tax']+100))*$v['unit_tax']*$v['goods_num'],2);
            $v['sale_tax_all'] = round(($v['sale_price']*($v['tax']/100))*$v['goods_num'],2);
//            $sale_money+=  round($v['sale_price']*$v['goods_num']*(1+$v['tax']/100),2);
            $supplier_cost+=round($v['unit_ht_price']*$v['goods_num'],2);
            $v['sale_tax_all'] = round(($v['sale_price']*($v['tax']/100))*$v['goods_num'],2);
            if($v['sfhj'] == 0.00){
                $v['sfhj'] = round($v['sale_price']*$v['goods_num']*(1+$v['tax']/100),2);
            }
//            $v['saleall'] = round($v['sale_price']*$v['goods_num']*(1+$v['tax']/100),2);

            $money['sale'] +=bcmul($v['goods_num'],$v['sale_price'],2);
            $money['purche'] +=bcmul($v['goods_num'],$v['unit_price'],2);
            $taxmoney['sale'] +=$v['sale_tax_all'];
            $taxmoney['purche'] +=$v['tax_all'];
            $allmoney['sale'] +=$v['sfhj'];
            $allmoney['purche'] +=$v['goods_num']*$v['unit_ht_price'];
            $allnum+=$v['goods_num'];
        }

        $srow = Supplier::find($row['supplier_id']);
        $row['supplier_name'] = $srow['nickname'];
        $crow = Customer::find($row['customer_id']);
        $row['customer_name'] = $crow['company'];
        if(empty($row['contacts'])){
            $row['contacts'] = $crow['nickname'];
        }
        if(empty($row['address'])){
            $row['address'] = $crow['address'];
        }
        if(empty($row['mobile'])){
            $row['mobile'] = $crow['mobile'];
        }

//        $sale_money = $sale_money+$row['allfare'];
        $unit_money = $supplier_cost+$row['unit_allfare'];

        $sale_money = $row['actual_cost'];

        $suppliers = Db::name('supplier')->select();
        $this->assign('suppliers',$suppliers);

        $this->assign('allnum',$allnum);
        $this->assign('money',$money);
        $this->assign('taxmoney',$taxmoney);
        $this->assign('allmoney',$allmoney);


        $this->assign('unit_money',$unit_money);
        $this->assign('sale_money',$sale_money);
        $this->assign('supplier_cost',$supplier_cost);
        $this->assign('row',$row);
        $this->assign('rows',$rows);

        return $this->view->fetch();
    }
    public function purchase($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }
        if ($this->request->isAjax()) {

            $supplier_id = input('supplier_id/d',0);
            if(empty($supplier_id)){
                $this->error('供应商不能为空');
            }
            $allfare_type = input('allfare_type/d',0);
            $allfare_supplier_id = input('allfare_supplier_id/d',0);
            if($allfare_type != 2){
                $allfare_supplier_id = 0;
            }


            $gdata = input('row/a');
            $unit_tax = input('unit_tax');
            foreach ($gdata as $v){
                if(empty($v['unit_price']) || $v['ht_price'] <0.001){
                    $this->error('采购单价不能为空');
                }
                if(empty($v['goods_num'] || $v['goods_num'] <1)){
                    $this->error('数量异常');
                }
            }
            $profit = config('site.profit');
            if(empty($profit)){
                $this->error('未设置厂家直发偏差值');
            }
            Db::startTrans();
            try {
                //总价格
                $unit_actual_cost = 0;
                //更新直发单进度
                //如果满足系统设置跳过审核 否则需要审核
                $status = 3;

                foreach ($gdata as $v){
                        $good_unit_price = bcmul($v['ht_price'],$v['goods_num'],4);
                        $unit_actual_cost = bcadd($unit_actual_cost,$good_unit_price,4);
                        $info = Db::name('factory_sales_goods')->where(array('id'=>$v['goods_id']))->find();
                        if(bcmul($v['unit_price'],(1+$profit/100),4) >$info['sale_price']){
                            $status = 2;
//                            break;
                        }
                }


                $res = $this->model->save(array(
                    'supplier_id' => $supplier_id,
                    'explain' => input('explain'),
                    'status' => $status,
                    'unit_allfare' => input('allfare/d',0),
                    'unit_actual_cost'=>$unit_actual_cost,
                    'unit_tax'=>$unit_tax,
                    'allfare_type'=>$allfare_type,
                    'allfare_supplier_id'=>$allfare_supplier_id,
                ), array('id' => $ids));

                if ($res) {
                    if($status == 3){
                        $this->addlog($ids);
                         //添加记录
                        $sales_log_id = Db::name('customer_sales_log')->insertGetId(array(
                             'customer_id'=>$row['customer_id'],
                             'type'=>'厂家直发单',
                             'type_id'=>2,
                             'number'=>$row['number'],
                             'source_id'=>$row['id'],
                             'createtime'=>time(),
                             'admin_id'=>$row['admin_id'],
                             'group_id'=>$row['group_id'],
                             'company'=>$row['company'],
                             'operator'=>$row['operator'],
                             'sales_num'=>$row['sales_num'],
                             'actual_cost'=>$row['actual_cost'],
                             'storehouse_id'=>$row['storehouse_id'],
                         ));
                        if(empty($sales_log_id)){
                            throw new Exception('数据异常');
                        }
                        foreach ($gdata as $v) {
                            $frow = Db::name('factory_sales_goods')->where(array('id'=>$v['goods_id']))->find();
                            if(empty($frow)){
                                throw new Exception('数据异常');
                            }
                            Db::name('goods_sales_log')->insert(array(
                                'goods_id' => $frow['goods_id'],
                                'type' => '厂家直发',
                                'type_id' => 2,
                                'number' => $row['number'],
                                'source_id' => $row['id'],
                                'createtime' => time(),
                                'admin_id'=>$row['admin_id'],
                                'group_id'=>$row['group_id'],
                                'company'=>$row['company'],
                                'operator'=>$row['operator'],
                                'storehouse_id'=>$row['storehouse_id'],
                                'sales_log_id'=>$sales_log_id,
                            ));
                        }
                    }
                    //设置产品属性
                    foreach ($gdata as $v){
                        $data[] = array(
                          'id'=>$v['goods_id'],
                          'unit_price'=>$v['unit_price'],
                          'unit_tax'=>$v['tax'],
                          'unit_ht_price'=>$v['ht_price'],
                          'remark'=>$v['remark'],
                        );
                    }
                    $fGoods = new fGoods();
                    $fGoods->saveAll($data);
                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '成功'
                    );
                }
                throw new Exception('错误异常');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $rows = Db::name('factory_sales_goods')
            ->field(' goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,sg.status,factory_sales_id')
            ->alias('sg')
            ->where(array('factory_sales_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        $sale_money = $row['actual_cost'];
//        foreach ($rows as $v){
//            $sale_money+=  round($v['sale_price']*$v['goods_num']*(1+$v['tax']/100),2);
//        }
//        $sale_money = $sale_money+$row['allfare'];
        $suppliers = Db::name('supplier')->select();
        $this->assign('sale_money',$sale_money);
//        $this->assign('supplier_cost',$supplier_cost);
        $this->assign('suppliers',$suppliers);
        $this->assign('row',$row);
        $this->assign('rows',$rows);

        return $this->view->fetch();
    }

    public function edit($ids = null){
        exit;
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
        $row = $this->model->find($ids);
//        $sGoods = new sGoods;
//        $goods = $sGoods->field('goods_id')->where(array('sales_slip_id'=>$ids))->select();
        if ($this->request->isAjax()) {

            $customer_id = input('customer_id/d',0);
            $supplier_id = input('supplier_id/d',0);

            if(empty($customer_id)){
                $this->error('客户不能为空');
            }
//            if(empty($supplier_id)){
//                $this->error('供应商不能为空');
//            }

            $tax = floatval(input('tax'));
//            if(!is_float($tax) || $tax >17){
//                $this->error('请检查税费');
//            }
            $explain = input('explain');
            $mobile = input('mobile');
            $address = input('address');
            $contacts = input('contacts');

            $allfare = input('allfare/d');
            $discount = input('discount');
            $discount_explain = input('discount_explain');
            $actual_cost = input('actual_cost');
            if(empty($actual_cost)){
                $this->error('费用计算错误');
            }
            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            $sdata = $params['row'];
//            $sgids = [];
            $sale_num=0;
            $allprice = 0;
            foreach ($sdata as $k=> $v){
//                $sdata[$k]['tax'] = floatval($v['tax']);
//                if(!is_float($sdata[$k]['tax'])){
//                    $this->error('商品'.$v['goods_id'].'税费设置有误');
//                }
                $sale_num +=$v['goods_num'];
//                $sgids[] = $v['goods_id'];
                $allprice+=$v['sfhj'];
            }
//            if($allprice+$allfare != $actual_cost){
            if(!compare($allprice+$allfare,$actual_cost)){
                $this->error('计算费用错误');
            }
//            $sGoods = new sGoods;
//            $idss = $sGoods->where(array('sales_slip_id'=>$ids))->select();

            $saledata = array(
                'supplier_id'=>$supplier_id,
                'allfare'=>$allfare,
                'discount'=>$discount,
                'discount_explain'=>$discount_explain,
                'actual_cost'=>$actual_cost,
                'customer_id'=>$customer_id,
                'explain'=>$explain,
                'address'=>$address,
                'mobile'=>$mobile,
                'contacts'=>$contacts,
                'tax'=>$tax,
                'sales_num'=>$sale_num,
            );

            Db::startTrans();
            try {
                $this->model->save($saledata,array('id'=>$ids));
                $gdata = [];
                $sGoods = new fGoods;
                $dres = $sGoods->where(array('factory_sales_id'=>$ids))->delete();

                if(!$dres){
                    throw new Exception('异常');
                }
                foreach ($sdata as $k => $v) {
                    $gdata[] = array(
                        'id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'ht_price' => $v['ht_price'],
                        'tax' => $v['tax'],
                        'sfhj' => $v['sfhj'],
                        'remark' => $v['remark'],
                        'factory_sales_id' => $ids,
                        'customer_id'=>$customer_id,
                        'supplier_id'=>$supplier_id,
                        'createtime'=>time(),
                    );
                }

                $sGoods = new fGoods;
                $sGoods->saveAll($gdata);
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'入库成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }


            exit;
        }

        $glist = Db::name('factory_sales_goods')
            ->field('sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,sfhj')
            ->alias('sg')
            ->where(array('factory_sales_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        $Customer = new Customer;
        $crow = $Customer->find($row['customer_id']);
        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('glist',$glist);
        $this->assign('row',$row);
        $this->assign('crow',$crow);
        $arr = explode('/',$_SERVER['REQUEST_URI']);

        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function afterpurchase($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }
        if ($this->request->isAjax()) {

            $supplier_id = input('supplier_id/d',0);
            if(empty($supplier_id)){
                $this->error('供应商不能为空');
            }
            $allfare_type = input('allfare_type/d',0);
            $allfare_supplier_id = input('allfare_supplier_id/d',0);
            if($allfare_type != 2){
                $allfare_supplier_id = 0;
            }


            $gdata = input('row/a');
            $unit_tax = input('unit_tax');
            foreach ($gdata as $v){
                if(empty($v['unit_price']) || $v['ht_price'] <0.001){
                    $this->error('采购单价不能为空');
                }
                if(empty($v['goods_num'] || $v['goods_num'] <1)){
                    $this->error('数量异常');
                }
            }
            foreach ($gdata as $v) {
                $frow = Db::name('factory_sales_goods')->where(array('id'=>$v['goods_id']))->find();
                if(empty($frow)){
                    throw new Exception('数据异常');
                }
            }
            $analysis = Db::name('analysis')->where(array(
                'source'=>12,
                'source_id' => $row['id'],
                'is_income'=>2,
                'storehouse_id' => $row['storehouse_id'],
            ))->find();
            if($analysis['status'] != 1){
                $this->error('财务状态异常,请处理');
            }

            Db::startTrans();
            try {
                //总价格
                $unit_actual_cost = 0;
                //更新直发单进度
                foreach ($gdata as $v){
                    $good_unit_price = bcmul($v['ht_price'],$v['goods_num'],4);
                    $unit_actual_cost = bcadd($unit_actual_cost,$good_unit_price,4);
                }

                $res = $this->model->save(array(
                    'supplier_id' => $supplier_id,
                    'explain' => input('explain'),
//                    'status' => $status,
                    'unit_allfare' => input('allfare/d',0),
                    'unit_actual_cost'=>$unit_actual_cost,
                    'unit_tax'=>$unit_tax,
                    'allfare_type'=>$allfare_type,
                    'allfare_supplier_id'=>$allfare_supplier_id,
                ), array('id' => $ids));

                Db::name('analysis')->where(array('id'=>$analysis['id']))->update(array('cost'=>$unit_actual_cost));

                if ($res) {
                    //设置产品属性
                    foreach ($gdata as $v){
                        $data[] = array(
                            'id'=>$v['goods_id'],
                            'unit_price'=>$v['unit_price'],
                            'unit_tax'=>$v['tax'],
                            'unit_ht_price'=>$v['ht_price'],
                            'remark'=>$v['remark'],
                        );
                    }
                    $fGoods = new fGoods();
                    $fGoods->saveAll($data);
                    Db::commit();
                    return array(
                        'code' => 1,
                        'msg' => '成功'
                    );
                }
                throw new Exception('错误异常');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $rows = Db::name('factory_sales_goods')
            ->field(' goods_id,sg.id,goods_num,sale_price,unit_ht_price,unit_tax,ht_price,tax,remark,title,place_origin,number,unit,specs,sg.status,factory_sales_id')
            ->alias('sg')
            ->where(array('factory_sales_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        $sale_money = $row['actual_cost'];

        $suppliers = Db::name('supplier')->select();
        $this->assign('sale_money',$sale_money);
        $this->assign('suppliers',$suppliers);
        $this->assign('row',$row);
        $this->assign('rows',$rows);
        return $this->view->fetch();
    }
    protected function addlog($ids){
        $row = $this->model->find($ids);

        $custrow = Customer::find($row['customer_id']);
        $suprow = Supplier::find($row['supplier_id']);
        if (empty($suprow)) {
            throw new Exception('供应商不能为空');
        }
        if (empty($suprow)) {
            throw new Exception('客户不能为空');
        }
        $cost = $row['unit_actual_cost']+$row['unit_allfare'];
        //自己承担运费 //把运费挂到 内名下
        if($row['allfare_type'] == 2){
            $allfare_suprow = Supplier::find($row['allfare_supplier_id']);
            $cost = $row['unit_actual_cost'];
            //支出
            Db::name('analysis')->insert(array(
                'is_income'=>2,
                'source'=>12,
                'cost'=>$row['unit_allfare'],
                'admin_id'=>$row['admin_id'],
                'group_id'=>$row['group_id'],
                'company'=>$row['company'],
                'operator'=>$row['operator'],
//            'admin_id'=>session('admin')['id'],
//            'group_id'=>$group['group_id'],
//            'company'=>$group['name'],
                'source_id' => $row['id'],
                'obj_id' => $row['allfare_supplier_id'],
//            'operator'=>session('admin')['nickname'],
                'controller'=>'factory/sales',
                'settle_name'=>$allfare_suprow['nickname'],
                'number'=>$row['number'],
                'createtime'=>time(),
                'explain'=>$row['explain'],//摘要
                'storehouse_id' => $row['storehouse_id'],
            ));
        }

        //支出
        $resss = Db::name('analysis')->insert(array(
            'is_income'=>2,
            'source'=>12,
            'cost'=>$cost,
            'admin_id'=>$row['admin_id'],
            'group_id'=>$row['group_id'],
            'company'=>$row['company'],
            'operator'=>$row['operator'],
//            'admin_id'=>session('admin')['id'],
//            'group_id'=>$group['group_id'],
//            'company'=>$group['name'],
            'source_id' => $row['id'],
            'obj_id' => $row['supplier_id'],
//            'operator'=>session('admin')['nickname'],
            'controller'=>'factory/sales',
            'settle_name'=>$suprow['nickname'],
            'number'=>$row['number'],
            'createtime'=>time(),
            'explain'=>$row['explain'],//摘要
            'storehouse_id' => $row['storehouse_id'],
        ));
        //应收
        $ress = Db::name('analysis')->insert(array(
            'is_income'=>1,
            'source'=>12,
            'cost'=>$row['actual_cost'],//不应该加运费
            'admin_id'=>$row['admin_id'],
            'group_id'=>$row['group_id'],
            'company'=>$row['company'],
            'source_id' => $row['id'],
            'obj_id' => $row['customer_id'],
            'operator'=>$row['operator'],
            'controller'=>'factory/sales',
            'settle_name'=>$custrow['company'],
            'number'=>$row['number'],
            'createtime'=>time(),
            'explain'=>$row['explain'],//摘要
            'storehouse_id' => $row['storehouse_id'],
        ));
        if (!$ress || !$resss) {
            throw new Exception('数据异常');
        }
    }
    public function examine2($ids = null){
        $row  = $this->model->find($ids);
        if(empty($row)){
            $this->error('暂无数据');
        }
        if ($this->request->isAjax()) {
            $params = input('row/a');
            if(empty($params['thumb']) && empty($params['remark'])){
                $this->error('至少选择一项内容输入');
            }
            $data = array(
                'image'=>$params['thumb'],
                'remark'=>$params['remark'],
                'type'=>12,
                'source_id'=>$ids,
            );

            Db::startTrans();
            try {
                $Voucher = new Voucher;
                $Voucher->save($data);

                $res = $this->model->save(array('status'=>4),array('id'=>$ids));
                if($res){
                    $sGoods = new fGoods;
                    $sGoods->save(array('status'=>2),array('factory_sales_id'=>$ids));
                    Db::commit();
                    return array(
                        'code'=>1,
                        'msg'=>'发货成功',
                    );
                }else{
                    throw new Exception('状态异常');
                }
                Db::rollback();
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }
        return $this->view->fetch();
    }
    public function examine3($ids = null){
        $row  = $this->model->find($ids);
        if(empty($row)){
            $this->error('暂无数据');
        }
        if ($this->request->isAjax()) {
            $params = input('row/a');
            if(empty($params['thumb']) && empty($params['remark'])){
                $this->error('至少选择一项内容输入');
            }
            $data = array(
                'image'=>$params['thumb'],
                'remark'=>$params['remark'],
                'type'=>12,
                'is_go'=>2,
                'source_id'=>$ids,
            );
            Db::startTrans();
            try {
                $Voucher = new Voucher;
                $Voucher->save($data);

                $res = $this->model->save(array('status'=>5),array('id'=>$ids));
                if($res){
                    Db::commit();
                    return array(
                        'code'=>1,
                        'msg'=>'到货成功',
                    );
                }else{
                    throw new Exception('状态异常');
                }
                Db::rollback();
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }
        return $this->view->fetch();
    }
    public function cancelbill($ids = null){
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        if(!$this->request->isAjax()){
            $this->error('非法操作');
        }
        $row = $this->model->find($ids);
        if($row['status'] == 1){
            $this->error('请直接关闭订单');
            //直接中止
            $this->model->save(array('status'=>7),array('id'=>$ids));
            $fgoods = new fGoods;
            if(!empty($row['sales_slip_id'])){
                $this->returnslip($row);
            }
            $fgoods->save(array('status'=>0),array('factory_sales_id'=>$ids));
            $this->success('成功');
        }


        if($row['status'] ==2 || $row['status'] >5){
            $this->error('状态异常');
        }
        $analysis = Db::name('analysis')->where(array(
            'source'=>12,
            'source_id' => $row['id'],
            'storehouse_id' => $row['storehouse_id'],
        ))->select();

        //只有财务数据在待处理的时候 才能处理
        foreach ($analysis as $v){
            if($v['status'] != 1){
                $this->error('财务状态异常,请处理');
            }
        }

        Db::startTrans();
        try {

            if(!empty($row['sales_slip_id'])){
                $this->returnslip($row);
            }
            //中止本单据
            $this->model->save(array('status'=>7),array('id'=>$ids));

            $fGoods = new fGoods();
            $ress = $fGoods->save(array('status'=>0),array('factory_sales_id'=>$ids));
            if (!$ress) {
                throw new Exception('数据异常');
            }

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

            //中止财务记录
            foreach ($analysis as $v){
                $ress = Db::name('analysis')->where(array(
                    'id' => $v['id']
                ))->update(array('status' => 4));
                if (!$ress) {
                    throw new Exception('数据异常');
                }
            }

            //添加中止记录
            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 12,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/diff',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));
            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'purchase/diff',
                'source_id'=>$ids,
                'source'=>12,
                'remark'=>'厂家直发',
                'number'=>isset($row['number'])?$row['number']:'',
            ));
            Db::commit();
            return array(
                'code'=>1,
                'msg'=>'成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }




    public function printing($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }

        $srow = Supplier::find($row['supplier_id']);
        $row['supplier_name'] = $srow['nickname'];
        $crow = Customer::find($row['customer_id']);
        $row['customer_name'] = $crow['company'];
        if(empty($row['contacts'])){
            $row['contacts'] = $crow['nickname'];
        }
        if(empty($row['address'])){
            $row['address'] = $crow['address'];
        }
        if(empty($row['mobile'])){
            $row['mobile'] = $crow['mobile'];
        }


        $money = array(
          'sale'=>0,
          'purche'=>0,
        );
        $taxmoney = array(
          'sale'=>0,
          'purche'=>0,
        );
        $allmoney = array(
          'sale'=>0,
          'purche'=>0,
        );

        $rows = Db::name('factory_sales_goods')
            ->field(' goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,sg.status,factory_sales_id,unit_price,unit_tax,unit_ht_price')
            ->alias('sg')
            ->where(array('factory_sales_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        foreach ($rows as &$v){
            $v['tax_all'] = round(($v['unit_ht_price']/($v['unit_tax']+100))*$v['unit_tax']*$v['goods_num'],2);
            $v['sale_tax_all'] = round(($v['sale_price']*($v['tax']/100))*$v['goods_num'],2);
            $v['saleall'] = round($v['sale_price']*$v['goods_num']*(1+$v['tax']/100),2);
            $money['sale'] +=$v['goods_num']*$v['sale_price'];
            $money['purche'] +=$v['goods_num']*$v['unit_price'];
            $taxmoney['sale'] +=$v['sale_tax_all'];
            $taxmoney['purche'] +=$v['tax_all'];
            $allmoney['sale'] +=$v['saleall'];
            $allmoney['purche'] +=$v['goods_num']*$v['unit_ht_price'];
        }
        $this->assign('money',$money);
        $this->assign('taxmoney',$taxmoney);
        $this->assign('allmoney',$allmoney);
        $this->assign('row',$row);
        $this->assign('rows',$rows);

        return $this->view->fetch();
    }
    //打印销售单
    public function printsale($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }

        $srow = Supplier::find($row['supplier_id']);
        $row['supplier_name'] = $srow['nickname'];
        $crow = Customer::find($row['customer_id']);
        $row['customer_name'] = $crow['company'];
        if(empty($row['contacts'])){
            $row['contacts'] = $crow['nickname'];
        }
        if(empty($row['address'])){
            $row['address'] = $crow['address'];
        }
        if(empty($row['mobile'])){
            $row['mobile'] = $crow['mobile'];
        }


        $money = array(
            'sale'=>0,
        );
        $taxmoney = array(
            'sale'=>0,
        );
        $allmoney = array(
            'sale'=>0,
        );

        $rows = Db::name('factory_sales_goods')
            ->field(' goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,sg.status,factory_sales_id,unit_price,unit_tax,unit_ht_price,sfhj')
            ->alias('sg')
            ->where(array('factory_sales_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        foreach ($rows as &$v){
            $v['tax_all'] = round(($v['unit_ht_price']/($v['unit_tax']+100))*$v['unit_tax']*$v['goods_num'],2);
            $v['sale_tax_all'] = round(($v['sale_price']*($v['tax']/100))*$v['goods_num'],2);
            if($v['sfhj'] == 0.00){
                $v['sfhj'] = round($v['sale_price']*$v['goods_num']*(1+$v['tax']/100),2);
            }
            $money['sale'] +=$v['goods_num']*$v['sale_price'];
            $taxmoney['sale'] +=$v['sale_tax_all'];
            $allmoney['sale'] +=$v['sfhj'];
        }
        $this->assign('money',$money);
        $this->assign('taxmoney',$taxmoney);
        $this->assign('allmoney',$allmoney);
        $this->assign('row',$row);
        $this->assign('rows',$rows);

        return $this->view->fetch();
    }
    //打印采购单
    public function printpurche($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }

        $srow = Supplier::find($row['supplier_id']);
        $row['supplier_name'] = $srow['nickname'];
        $crow = Customer::find($row['customer_id']);
        $row['customer_name'] = $crow['company'];
        if(empty($row['contacts'])){
            $row['contacts'] = $crow['nickname'];
        }
        if(empty($row['address'])){
            $row['address'] = $crow['address'];
        }
        if(empty($row['mobile'])){
            $row['mobile'] = $crow['mobile'];
        }


        $money = array(
          'sale'=>0,
          'purche'=>0,
        );
        $taxmoney = array(
          'sale'=>0,
          'purche'=>0,
        );
        $allmoney = array(
          'sale'=>0,
          'purche'=>0,
        );

        $rows = Db::name('factory_sales_goods')
            ->field(' goods_id,sg.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,sg.status,factory_sales_id,unit_price,unit_tax,unit_ht_price')
            ->alias('sg')
            ->where(array('factory_sales_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        foreach ($rows as &$v){
            $v['tax_all'] = round(($v['unit_ht_price']/($v['unit_tax']+100))*$v['unit_tax']*$v['goods_num'],2);
            $v['sale_tax_all'] = round(($v['sale_price']*($v['tax']/100))*$v['goods_num'],2);
            $v['saleall'] = round($v['sale_price']*$v['goods_num']*(1+$v['tax']/100),2);
            $money['sale'] +=$v['goods_num']*$v['sale_price'];
            $money['purche'] +=$v['goods_num']*$v['unit_price'];
            $taxmoney['sale'] +=$v['sale_tax_all'];
            $taxmoney['purche'] +=$v['tax_all'];
            $allmoney['sale'] +=$v['saleall'];
            $allmoney['purche'] +=$v['goods_num']*$v['unit_ht_price'];
        }
        $this->assign('money',$money);
        $this->assign('taxmoney',$taxmoney);
        $this->assign('allmoney',$allmoney);
        $this->assign('row',$row);
        $this->assign('rows',$rows);

        return $this->view->fetch();
    }
    //关闭订单
    public function del($ids = null){
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('单据不存在');
        }
        Db::startTrans();
        try {
            //修改单据状态
            $res = $this->model->save(array('status'=>8),array('id'=>$ids));
            if(empty($res)){
                throw new Exception('单据异常');
            }
            //修改单据商品状态
            $fgoods = new fGoods;
            $fgoods->save(array('status'=>0),array('factory_sales_id'=>$ids));
            //关闭订单联动销售单

            if(!empty($row['sales_slip_id'])){
                $this->returnslip($row);
            }
            Db::commit();
            return array(
              'code'=>1,
              'msg'=>'关闭订单成功',
            );
        }catch (\Exception $e) {
//                dump($e);
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
//
//        $res = $this->model->save(array('status'=>8),array('id'=>$ids));
//        if($res){
//            $this->success('关闭订单成功');
//        }
//        $this->error('关闭失败');
    }
    protected function  returnslip($row){
        $srow = Db::name('sales_slip')->where(array('id'=>$row['sales_slip_id']))->find();
        if($srow['status'] ==2|| $srow['status'] == 3){
            $farows = Db::name('factory_sales_goods')->where(array('factory_sales_id'=>$row['id']))->select();
            foreach ($farows as $v){
                Db::name('sales_goods')->where(array('sales_slip_id'=>$row['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>1));
            }
        }

        if($srow['status'] == 4|| $srow['status'] == 5){//部分转换
            Db::name('sales_slip')->where(array('id'=>$row['sales_slip_id']))->update(array('status'=>3));
            $farows = Db::name('factory_sales_goods')->where(array('factory_sales_id'=>$row['id']))->select();

            foreach ($farows as $v){
                Db::name('sales_goods')->where(array('sales_slip_id'=>$row['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>1));
            }

        }
        if($srow['status'] == 8){//整单装换
            Db::name('sales_slip')->where(array('id'=>$row['sales_slip_id']))->update(array('status'=>2));
            Db::name('sales_goods')->where(array('sales_slip_id'=>$row['sales_slip_id'],'status'=>6))->update(array('status'=>1));
        }
    }
}
